<?php
class User extends Base
{
    public static $_passwordHash = "abcdefcghiklmnopqrstuvwxyz123457890!@#$%&*()_+";
    private $_userId;
    private $_userName;
    private $_password;
    private $_type;
    private $_realName;
    private $_nickName;
    private $_gender;
    private $_age;
    private $_experience;
    private $_hobby;
    private $_avatar;
    private $_createDate;
    private $_updateDate;
    private $_lastLoginDate;
    private $_ip;

    public function delete($id)
    {
        try {
            $user_delete_sql = "delete from " . $this->getTableName() . " where " . $this->getPrimaryKey() . "=" . $id;
            $application_vote_delete_sql = "delete from application_vote where applicationId in (select applicationId from applications where userId=" . $id . ")";
            $application_delete_sql = "delete from applications where userId=" . $id;
            $comment_delete_sql = "delete from comment where userId=" . $id;
            $this->_db->beginTransaction();
            $this->_db->query($user_delete_sql);
            $this->_db->query($application_vote_delete_sql);
            $this->_db->query($application_delete_sql);
            $this->_db->query($comment_delete_sql);
            $this->_db->commit();
        } catch (Exception $e) {
            $this->_db->rollBack();
            echo $e->getMessage();
        }
    }

    protected function getPrimaryKey()
    {
        return "userId";
    }

    protected function getTableName()
    {
        return "user";
    }


    public function cookieLogin()
    {
        $userRecord = $this->_db->getOne("select * from " . $this->getTableName() . " where userName='" . $this->getUserName() . "'");
        if ($userRecord['userId'] > 0) {
            $this->mapping($userRecord);
            $_SESSION['credentials'] = array("userId" => $this->getUserId(), "userName" => $this->getUserName(), "realName" => $this->getRealName(), "type" => $this->getType(), "lastLoginDate" => $this->getLastLoginDate(), "ip" => $this->getIp());
            $this->updateLastLogin();
            //保存凭据
            return true;
        }
        return false;

    }

    /**登录用户认证
     * @return void
     */
    public function auth()
    {
        try {
            if ($this->_userName == null || $this->_password == null) return false;
            $user_name_sql = "select * from user where userName ='" . $this->_userName . "'";
            $currentUser = $this->_db->getOne($user_name_sql);
            if ($currentUser['password'] == $this->getEncodePassword() && $currentUser['type'] == $this->getType()) {
                $this->setUserId($currentUser['userId']);
                $_SESSION['credentials'] = array("userId" => $currentUser['userId'], "userName" => $currentUser['userName'], "realName" => $currentUser['realName'], "type" => $currentUser['type'], "lastLoginDate" => $currentUser['lastLoginDate'], "ip" => $currentUser['ip']);
                $this->updateLastLogin();
                //保存凭据
                return true;
            }
        }
        catch (ErrorException $e) {
            return false;
        }
        return false;

    }

    /**用户注册，涉及到同步注册，因此采用失误
     * @return void
     */
    public function signup($post)
    {
        define('IN_DISCUZ', "TEMP_USE");
        include_once(ROOT . "/bbs/include/global.func.php");
        //开启式事务
        if ($this->canUserNameRegistered($post['userName'])) {
            try {
                $baola_user_register_sql = "insert into user (userName,password,email,type,question,answer,createDate,updateDate,lastLoginDate) values ('" . $post['userName'] . "','" . md5($post['password'] . User::$_passwordHash) . "','" . $post['email'] . "','user','" . $post['question'] . "','" . $post['answer'] . "',now(),now(),now())";
                $pass = random(6);
                $uc_center_user_register_sql = "insert into cdb_uc_members(username,password,email,salt) values ('" . $post['userName'] . "','" . md5(md5($post['password']) . $pass) . "','" . $post['email'] . "','" . $pass . "')";
                $bbs_user_register_sql = "insert into cdb_members(username,password,email,groupid) values ('" . $post['userName'] . "','" . md5($post['password']) . "','" . $post['email'] . "',10)";
                $this->_db->beginTransaction();
                $this->_db->query($baola_user_register_sql);
                $this->_db->query($uc_center_user_register_sql);
                $this->_db->query($bbs_user_register_sql);
                $this->_db->commit();
            } catch (Exception $e) {
                $this->_db->rollBack();
                echo $e->getMessage();
            }
            return true;
        }
        return false;


    }

    public function resetPassword($userName, $newPassword)
    {
        define('IN_DISCUZ', "TEMP_USE");
        include_once(ROOT . "/bbs/include/global.func.php");
        //开启式事务
        $user = $this->loadByUserName($userName);
        if ($user['userId'] > 0) {
            try {
                $baola_user_update_sql = "update user set password='" . md5($newPassword . User::$_passwordHash) . "' where userName = '" . $userName . "'";
                $pass = random(6);
                $uc_center_user_update_sql = "update cdb_uc_members set password= '" . md5(md5($newPassword) . $pass) . "',salt='" . $pass . "' where username='" . $userName . "'";
                $bbs_user_update_sql = "update cdb_members set password ='" . md5($post['password']) . "' where username='" . $userName . "'";
                $this->_db->beginTransaction();
                $this->_db->query($baola_user_update_sql);
                $this->_db->query($uc_center_user_update_sql);
                $this->_db->query($bbs_user_update_sql);
                $this->_db->commit();
            } catch (Exception $e) {
                $this->_db->rollBack();
                echo $e->getMessage();
            }
            return true;
        }
        return false;
    }


    public function updateLastLogin()
    {
        $sql = "update user set lastLoginDate = '" . Util::getCurrentDate() . "',ip='" . Util::getClientIp() . "' where " . $this->getPrimaryKey() . "=" . $this->getUserId();
        $this->_db->update($sql);
        return true;
    }

    public function getAll()
    {
        return $this->_db->getall("select * from user");
    }

    public function getMyUcMemberId()
    {
        $count = $this->_db->getOne("select * from cdb_members where username='" . $this->getUserName() . "'");
        return $count['uid'];
    }

    public function getEncodePassword()
    {
        return md5($this->_password . User::$_passwordHash);
    }

    public function getType()
    {
        return $this->_type;
    }

    public function setAge($age)
    {
        $this->_age = $age;
    }

    public function getAge()
    {
        return $this->_age;
    }

    public function setAvatar($avatar)
    {
        $this->_avatar = $avatar;
    }

    public function getAvatar()
    {
        return $this->_avatar;
    }

    public function setCreateDate($createDate)
    {
        $this->_createDate = $createDate;
    }

    public function getCreateDate()
    {
        return $this->_createDate;
    }

    public function setExperience($experience)
    {
        $this->_experience = $experience;
    }

    public function getExperience()
    {
        return $this->_experience;
    }

    public function setGender($gender)
    {
        $this->_gender = $gender;
    }

    public function getGender()
    {
        return $this->_gender;
    }

    public function setHobby($hobby)
    {
        $this->_hobby = $hobby;
    }

    public function getHobby()
    {
        return $this->_hobby;
    }

    public function setNickName($nickName)
    {
        $this->_nickName = $nickName;
    }

    public function getNickName()
    {
        return $this->_nickName;
    }

    public function setPassword($password)
    {
        $this->_password = $password;
    }

    public function getPassword()
    {
        return $this->_password;
    }


    public function setRealName($realName)
    {
        $this->_realName = $realName;
    }

    public function getRealName()
    {
        return $this->_realName;
    }

    public function setUpdateDate($updateDate)
    {
        $this->_updateDate = $updateDate;
    }

    public function getUpdateDate()
    {
        return $this->_updateDate;
    }

    public function setUserId($userId)
    {
        $this->_userId = $userId;
    }

    public function getUserId()
    {
        return $this->_userId;
    }

    public function setUserName($userName)
    {
        $this->_userName = $userName;
    }

    public function getUserName()
    {
        return $this->_userName;
    }

    public function setType($type)
    {
        $this->_type = $type;
    }

    public function setLastLoginDate($lastLoginDate)
    {
        $this->_lastLoginDate = $lastLoginDate;
    }

    public function getLastLoginDate()
    {
        return $this->_lastLoginDate;
    }

    public function setIp($ip)
    {
        $this->_ip = $ip;
    }

    public function getIp()
    {
        return $this->_ip;
    }

    public function canUserNameRegistered($userName)
    {
        $baona_sql = "select count(1) as count from user where userName ='" . $userName . "'";
        $baona_user = $this->_db->getOne($baona_sql);
        $uc_sql = "select count(1) as count from cdb_uc_members where username ='" . $userName . "'";
        $uc_user = $this->_db->getOne($uc_sql);
        $discuz_sql = "select count(1) as count from cdb_members where username ='" . $userName . "'";
        $discuz_user = $this->_db->getOne($discuz_sql);
        return $baona_user['count'] == 0 && $uc_user['count'] == 0 && $discuz_user['count'] == 0;
    }

    public function loadByUserName($userName)
    {
        $user_name_sql = "select * from user where userName ='" . $userName . "'";
        return $this->_db->getOne($user_name_sql);
    }

    public function loadByUserNameAndEmail($userName, $email)
    {
        $user_name_sql = "select * from user where userName ='" . $userName . "' and email='" . $email . "'";
        return $this->_db->getOne($user_name_sql);
    }

    public function loadByUserNameAndEmailAndAnswer($userName, $email, $answer)
    {
        $user_name_sql = "select * from user where userName ='" . $userName . "' and email='" . $email . "' and answer='" . $answer . "'";
        return $this->_db->getOne($user_name_sql);
    }

    protected function competeRecord($post)
    {
        return array("realName" => $post['name'],
                     "gender" => $post['gender'],
                     "nickname" => $post['nickname'],
                     "avatar" => $post['avatar']);
    }

}

?>